package controllers.api;

import java.io.IOException;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import play.mvc.Controller;

public class API extends Controller {
	public static class Error {
		private String type;
		private String message;
		public String getType() {
			return type;
		}
		public String getMessage() {
			return message;
		}
		public Error(String type,String message) {
			this.type = type;
			this.message = message;
		}
	}

	private static ObjectMapper mapper = new ObjectMapper();
	static {
		mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
	}
	
	protected static void json(List<play.data.validation.Error> errors){
		Map<String,Object> result = new LinkedHashMap<String, Object>();
		List<API.Error> list = new ArrayList<API.Error>();
		for(play.data.validation.Error err:errors){
			list.add(new Error(err.getKey(), err.message()));
		}
		result.put("error", list.size()==1?list.get(0):list);
		json(result);
	}
	
	protected static void json(Object object){
    	try {
    		renderJSON(mapper.writeValueAsString(object));
    	} catch (IOException e) {
			json(e.getMessage());
		}
    }
}
